<?php
require_once "site_config.php";
require_once "ra_global.php";
// 油码验证，优惠码验证
$method = $_GET['method'];
if($method == "checkanswer"){
    $qid = $_GET['qid'];
    $aid = $_GET['aid'];
    $uid = $_GET['uid'];

    echo checkAnswerResult($db, $qid, $aid, $uid);
}

function checkAnswerResult($db, $qid, $aid, $uid) {
    $result = array();
    $success = true;
    $errcode = 0;
    $title = '';
    $detail = '';
    $nomore = '';

    $result1 = true;
    $db->ig2_query('BEGIN');

    $user=$db->ig2_want('mae_user','id='.$uid);
    $answer=$db->ig2_want('mae_answer','id='.$aid);

    if($answer['bingo'] == 0){
        $rightAnswer = $db->ig2_want('mae_answer','question_id='.$qid.' AND bingo=1');
        $title = '回答错误：不加分';
        $detail = '正确答案是：'.$rightAnswer['content'];
        $errcode = 0;
    }else{
        $title = '回答正确：加10分';
        $db->ig2_update('mae_user',array('score'=>$user['score']+10),'id='.$uid);
        $errcode = 1;
    }

    $value=array(
        'id'			=>'',
        'uid'			=>$uid,
        'qid'			=>$answer['question_id'],
        'result'		=>$answer['bingo'],
        'create_time'	=>time(),
    );
    $result1=$db->ig2_insert('mea_user_answer_record',$value);
    $success=$success && $result1?true:false;

    if ($success) {
        if(trim($user['answer_ids'])){
            $answer_ids_arr=explode(',',$user['answer_ids']);
        }else{
            $answer_ids_arr=array();
        }
        array_push($answer_ids_arr,$_GET['qid']);
        $answer_ids_str=implode(',',$answer_ids_arr);
        $result1=$db->ig2_update('mae_user',array('answer_ids'=>$answer_ids_str),'id='.$uid);
        $success=$success && $result1?true:false;
    }

    // 判断是否还有下一题
    $user=$db->ig2_want('mae_user','id='.$uid);
    $sells=count($db->ig2_select('mae_sell','uid='.$uid.' and create_time >= 1447070400'));
    $answer_ids=explode(',',$user['answer_ids']);
    $count_answer_ids=trim($user['answer_ids'])?count($answer_ids):0;
    $surplus=$sells>2?(floor($sells/3)-$count_answer_ids):0;
    $surplus=$surplus>0?$surplus:0;

    if (!$surplus) {
        $nomore = '您目前已没有答题机会，欢迎继续扫油答题！';
    }

    if ($success) {
        $db->ig2_query('COMMIT');
        $result['errcode'] = $errcode;
        $result['title'] = $title;
        $result['detail'] = $detail;
        $result['nomore'] = $nomore;
    } else {
        $db->ig2_query('ROLLBACK');
        $result['errcode'] = 2;
        $result['title'] = '服务器异常';
    }

    return json_encode($result);
}
?>